//
//  PushMessageViewController.m
//  BGM
//
//  Created by liuqin on 2018/12/3.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "PushMessageViewController.h"
#import "PushTypeView.h"
#import "Common.h"
#import "MeTableViewCell.h"
#import "BGMHTTP.h"
#import "BGMUser.h"
#import "PushAddImageTableViewCell.h"
#import "PushSuccessViewController.h"
#import "MessagePayViewController.h"
#import "BGMApplePayViewController.h"
#import "PushShieldFriendViewController.h"

#import <MobileCoreServices/MobileCoreServices.h>
//#import "ZYQAssetPickerController.h"
#import "AFHTTPSessionManager.h"
//ASSet需要导入
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import "QBImagePickerController.h"
#import "BGMCity.h"
#import "SVProgressHUD.h"


#import "QiniuSDK.h"
#import "GCQiniuUploadManager.h"
#import "BGMNewImage.h"
#import "PushImageClass.h"

#import "GFAddressPicker.h"

#define  _maxLength 14


@interface PushMessageViewController ()
<MeTableViewCellDelegate,
UITableViewDelegate,UITableViewDataSource,
PushTypeViewDelegate,PushAddImageTableViewCellDelegate,
UITextFieldDelegate,UITextViewDelegate,
UIImagePickerControllerDelegate,UINavigationControllerDelegate,
QBImagePickerControllerDelegate,
GFAddressPickerDelegate>
@property (nonatomic, strong)PushTypeView *bgView;
@property (nonatomic, strong)UITableView *messageTable;
@property (nonatomic, strong)NSArray *cellArray;
@property (nonatomic, strong)NSMutableString *imageStr;

@property (nonatomic, assign)float imageH; //
@property (nonatomic, strong)GFAddressPicker *pickerView;


@property (nonatomic, strong)NSString *pushTitle; //标题
@property (nonatomic, strong)NSString *pushContent; //内容
@property (nonatomic, strong)NSMutableArray *imageArray; //内容


@property (nonatomic,strong) UIImagePickerController *imagePickerController;
@property (nonatomic,strong) QBImagePickerController *qb_picker;


@property (nonatomic, strong)NSString *red;//有否有帮转红包
@property (nonatomic, assign)BOOL isRed;//是否有偿
@property (nonatomic, strong)NSString *orderID;//订单号


@property (nonatomic, strong)NSString *userCity;

@property (nonatomic, strong)NSString *noseeFriend; //不让谁看

@property (nonatomic, assign)BOOL isPushing;//是否有偿


@end

@implementation PushMessageViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    self.backBtn.hidden = NO;

    self.userCity = @"";
    self.noseeFriend = @"";
    
    [self.titleBtn setTitle:self.titleStr forState:UIControlStateNormal];
    self.titleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.titleBtn setImage:[UIImage imageNamed:@"puch_down"] forState:UIControlStateNormal];
    self.imageArray = [[NSMutableArray alloc]init];
    self.imageStr = [[NSMutableString alloc]init];
    self.titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -30, 0, 0);
    self.titleBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 35, 0, 0);
    [self.titleBtn addTarget:self action:@selector(clickTitleBtn) forControlEvents:UIControlEventTouchUpInside];
    
    self.imageH = 130.0f;
    
    self.messageTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height)];
    self.messageTable.delegate = self;
    self.messageTable.dataSource = self;
    self.messageTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.messageTable];
    
    self.cellArray = @[@"帮转红包",@"是否有偿",@"所在位置",@"不让谁看"];
    
    self.bgView = [[PushTypeView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height)];
    self.bgView.delegate = self;
    [self.bgView pushType:self.typeArray];
    
    [self.view addSubview:self.bgView];
    self.bgView.hidden = YES;
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPayMoney:) name:@"pay_money" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushVCDismiss) name:@"pushVCDismiss" object:nil];
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newSeeFriend:) name:@"newSeeFriend" object:nil];
    
    self.pickerView = [[GFAddressPicker alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.pickerView.delegate = self;
    self.pickerView.font = [UIFont boldSystemFontOfSize:18];
    [self.view addSubview:self.pickerView];
    self.pickerView.hidden = YES;

}
#pragma mark 请求订单信息
- (void)getPayMoney:(NSNotification *)noti{
    NSString *money = noti.object;
    self.red = money;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
    [self.messageTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    
}

#pragma mark 切换标题
- (void)clickTitleBtn{
    if (self.bgView.hidden) {
        [UIView animateWithDuration:1 animations:^{
            self.bgView.frame = CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH);
            self.bgView.hidden = NO;
            
        }];
    }else{
        [UIView animateWithDuration:1 animations:^{
            self.bgView.frame = CGRectMake(0, self.navview.frame.size.height, SCREENW, 0);
            self.bgView.hidden = YES;
        }];
    }
}
-(void)clickType:(NSDictionary *)dic{
    self.typeId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
    self.titleStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
    [self.titleBtn setTitle:self.titleStr forState:UIControlStateNormal];
    
    [UIView animateWithDuration:1 animations:^{
        self.bgView.frame = CGRectMake(0, self.navview.frame.size.height, SCREENW, 0);
        self.bgView.hidden = YES;
    }];
}
#pragma mark tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 8;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row ==0) {
        return 45;
    }else if (indexPath.row ==1){
        return 120;
    }else if (indexPath.row ==2){
        return self.imageH;
    }else if(indexPath.row ==7){
        return 100;
    }
    
    else{
        return 45;
    }
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row ==0) {
        static NSString *indention = @"cell0";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indention];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indention];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(15, 15, SCREENW, 30)];
            textField.placeholder = @"帮忙主题（限15字内）";
            textField.textColor = bgmmainColor;
            textField.returnKeyType = UIReturnKeyDone;
            textField.tag = 100;
            textField.delegate = self;
            [cell addSubview:textField];
            [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
            UILabel *line =[[UILabel alloc]initWithFrame:CGRectMake(0, 44, SCREENW, 0.3)];
            line.backgroundColor = [UIColor grayColor];
            line.alpha = 0.3;
            [cell addSubview:line];
        }
        return cell;
    }
    else if (indexPath.row ==1){
        static NSString *indention = @"cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indention];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indention];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UILabel *bglabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 17, SCREENW, 20)];
            bglabel.text = @"帮忙说明...";
            bglabel.textColor = bgmsmallColor;
            bglabel.font = [UIFont systemFontOfSize:15];
            bglabel.tag = 100;
            [cell addSubview:bglabel];
            
            UITextView *testView =[[UITextView alloc]initWithFrame:CGRectMake(15, 10, SCREENW-30, 100)];
            testView.backgroundColor = [UIColor clearColor];
            testView.textColor = bgmmainColor;
            testView.font = [UIFont systemFontOfSize:15];
            testView.returnKeyType = UIReturnKeyDone;
            testView.delegate = self;

            [cell addSubview:testView];
        }
        
        
        
        return cell;
    }
    else if (indexPath.row == 2){
        static NSString *indention = @"PushAddImageTableViewCell";
        PushAddImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indention];
        if (cell == nil) {
            cell = [[PushAddImageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indention];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.photoDelegate = self;

        }
        [cell setSeleImage:self.imageArray];
        return cell;
    }
    else if (indexPath.row== 7){
        static NSString *indention = @"cell7";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:indention];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indention];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UIButton *pushBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 40, SCREENW-30, 45)];
            pushBtn.backgroundColor = bgmyelloeColor;
            [pushBtn setTitle:@"发布" forState:UIControlStateNormal];
            pushBtn.layer.cornerRadius = 5;
            pushBtn.layer.masksToBounds = YES;
            pushBtn.tag = 99;
            [cell addSubview:pushBtn];
        }
        UIButton *btn = (UIButton *)[cell viewWithTag:99];
        [btn addTarget:self action:@selector(clickPush) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    
    }
    else{
        static NSString *identifier = @"MeTableViewCell";
        MeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[MeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.iconBtn.hidden = YES;  //icon

            cell.contentLabel.frame = CGRectMake(15, 0, 300, 50);
            cell.contentLabel.font = [UIFont systemFontOfSize:16];
            cell.rightLabel.frame = CGRectMake(SCREENW-250, 0, 210,50 );
            cell.rightLabel.backgroundColor = [UIColor clearColor];
            cell.rightLabel.hidden = NO;  //Lable
            cell.rightLabel.textColor = bgmsmallColor;
            cell.rightLabel.font = [UIFont systemFontOfSize:14];
            cell.meCellDelegate = self;

        }
        
        cell.rightSwitch.hidden = YES;
        cell.rightBtn.hidden = NO;

        cell.contentLabel.text = [self.cellArray objectAtIndex:(int)(indexPath.row)-3];
        if(indexPath.row == 3){  //帮转红包
            
            if (self.red.length==0) {
                cell.rightLabel.text = @"发个红包让更多人帮忙转发";
            }else{
                 cell.rightLabel.text =[NSString stringWithFormat:@"%@元",self.red];
            }
        }else if (indexPath.row == 4){//是否有偿
            cell.rightBtn.hidden = YES;
            cell.rightSwitch.hidden = NO;
            cell.rightSwitch.frame = CGRectMake(SCREENW-70, 10, 60, 30);
            cell.rightSwitch.on = self.isRed;
        }else if (indexPath.row == 5){ //位置
            if(self.userCity.length==0){
                cell.rightLabel.text = @"选择所在城市";
            }else{
                cell.rightLabel.text = self.userCity;
            }
          
        }else if (indexPath.row == 6){  //不给谁看
            if(self.noseeFriend.length==0){
                cell.rightLabel.text = @"选择屏蔽好友";
            }else{
                cell.rightLabel.text = self.noseeFriend;
            }
        }
        return cell;
        
    }
}
-(void)seleSwitch:(BOOL)b{
    self.isRed = b;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row ==3){
        if(self.red.length==0){
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSString *openSet = [userDefaults objectForKey:@"openSet"];
            if ([openSet isEqualToString:@"YES"]) {
                [self showPayView];
            }else{
                [self showApplePay];
            }

        }else{
            [SVProgressHUD showInfoWithStatus:@"金额不能修改"];
        }
    }else if (indexPath.row ==5){
        self.pickerView.hidden = NO;
    }else if (indexPath.row ==6){
        PushShieldFriendViewController *vc = [[PushShieldFriendViewController alloc]init];
        vc.isPush = YES;
        vc.vcTitle = @"屏蔽好友";
        [self presentViewController:vc animated:YES completion:nil];
    }
    
}



- (void)showApplePay{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消 " style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                         }];
    UIAlertAction* applePay = [UIAlertAction actionWithTitle:@"苹果支付" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * action) {
                                                         //响应事件
                                                         //
                                                         [self gotoApplePay];
                                                     }];
    [alert addAction:applePay];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)showPayView{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消 " style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                             NSLog(@"action = %@", action);
                                                         }];
    UIAlertAction* aliPay = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action) {
                                                       //响应事件
                                                       [self gotoPayVC];
                                                   }];
    UIAlertAction* applePay = [UIAlertAction actionWithTitle:@"苹果支付" style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction * action) {
                                                         //响应事件
                                                         //
                                                         [self gotoApplePay];
                                                     }];
    [alert addAction:aliPay];
    [alert addAction:applePay];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)gotoPayVC{
    MessagePayViewController *vc = [[MessagePayViewController alloc]init];
    vc.type = BGMPushildRed;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)gotoApplePay{
    BGMApplePayViewController *vc = [[BGMApplePayViewController alloc]init];
    vc.type = BGMPushildRed;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)upSomeImage{
 

    NSMutableArray *imageData = [[NSMutableArray alloc]init];
    for (int i = 0;i<self.imageArray.count;i++) {
        BGMNewImage *newImage = [[BGMNewImage alloc]init];
        UIImage *image = [self.imageArray objectAtIndex:i];
        NSData *data = [newImage resetSizeOfImageData:image maxSize:1024];
        PushImageClass *imageclass = [[PushImageClass alloc]init];
        imageclass.imageData = data;
        imageclass.isCompele = NO;
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
        NSString *name = [NSString stringWithFormat:@"%d_%@_iosPush.png",i,timeString];
        imageclass.fileName = name;
        [imageData addObject:imageclass];
    }
    
    NSString *token =  [[GCQiniuUploadManager sharedInstance] createToken];
    [self uploadFileWithImages:imageData index:0 token:token completed:^(NSArray<PushImageClass *> *list){

        dispatch_async(dispatch_get_main_queue(), ^{
            for (PushImageClass *imageClass in list) {
                [self.imageStr appendFormat:@"%@,",imageClass.fileUrl];
            }
            [self pushMessage];
            
        });

    }];
  

}

- (void)uploadFileWithImages:(NSArray<PushImageClass *> *)entitys index:(NSInteger)index token:(NSString *)token
                   completed:(void (^)(NSArray<PushImageClass *> *list))completion{
    
    if(index>=0&&index<[entitys count]){
        PushImageClass *entity = entitys[index];
        [self uploadFileWithToken:token push:entity completed:^(NSString *url,BOOL boo){
            
            if(boo){
                entity.fileUrl = url;
            }
            entity.isCompele=boo;
            
            if(index+1 >[entitys count]-1){
                if (completion) {
                    completion(entitys);
                }
            }else{
                [self uploadFileWithImages:entitys index:index+1 token:token completed:completion];
            }
            
        }];
    }
    
}

- (void)uploadFileWithToken:(NSString *)token push:(PushImageClass *)entity
                  completed:(void (^)(NSString *url,BOOL boo))success
{
    
    
    NSData *data = entity.imageData;
    if (!data) {
        if (success) {
            success(nil,NO);
        }
        return;
    }
    
    
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *up = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    
    [upManager putData:data key:entity.fileName token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSString *url = [NSString stringWithFormat:@"http://yaobangma.com/%@",[resp objectForKey:@"key"]];
        if (success) {
            success(url,YES);
        }
    } option:up];
    
    
}





- (void)upOneImage{
    
    BGMNewImage *newImage = [[BGMNewImage alloc]init];
    UIImage *image = [self.imageArray objectAtIndex:0];
    NSData *data = [newImage resetSizeOfImageData:image maxSize:1024];
    
    NSString *token =  [[GCQiniuUploadManager sharedInstance] createToken];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *up = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
       
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    NSString *name = [NSString stringWithFormat:@"%@_iosPush.png",timeString];
    
    [upManager putData:data key:name token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSString *url = [NSString stringWithFormat:@"http://yaobangma.com/%@",[resp objectForKey:@"key"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self getImageURL:url];
        });
    } option:up];
 
}
- (void)getImageURL:(id)idStr{
    if ([idStr isKindOfClass:[NSString class]]) {
        [self.imageStr appendString:idStr];
    }else{
        NSArray *array = idStr;
        for (NSString *url in array) {
            [self.imageStr appendFormat:@"%@", [NSString stringWithFormat:@"%@,",url]];
        }
    }
    
    [self pushMessage];
}

- (void)newSeeFriend:(NSNotification *)notification{
    self.noseeFriend = notification.object;
    if(self.noseeFriend.length>0){
        self.noseeFriend = [self.noseeFriend substringWithRange:NSMakeRange(0, self.noseeFriend.length-1)];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
        [self.messageTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    
}
#pragma mark --发布--
- (void)clickPush{
    
    if (self.pushTitle.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入标题"];
        return;
    }else if (self.pushContent.length ==0){
        [SVProgressHUD showInfoWithStatus:@"请输入内容"];
        return ;
    }
    
    
    if (self.isPushing) {
        return;
    }
    UIView *pushView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    pushView.backgroundColor = [UIColor blackColor];
    pushView.alpha = 0.3;
    [self.view addSubview:pushView];
    
    self.isPushing = YES;
    
    
    [SVProgressHUD showWithStatus:@"正在发布"];

    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    
    [self pushImage];

}
#pragma mark 上传图片1/多张
- (void)pushImage{
    

    
    if (self.imageArray.count ==0) {
        [self.imageStr appendFormat:@""];
        [self pushMessage];
    }else if (self.imageArray.count==1) {
        [self upOneImage];
    }else{
        [self upSomeImage];
    }
}
#pragma mark 发布

- (void)pushMessage{
    NSString *itIsPaid = self.isRed?@"1":@"2";
    /////////
//    self.red = @"0.01";
    
    BGMUser *user = [BGMUser shareInstance];
    NSDictionary *params = @{@"userId":user.userId,
                             @"userToken":user.userToken,
                             @"typeId":self.typeId,
                             @"publishTitle":self.pushTitle,
                             @"publishContent":self.pushContent,
                             @"filterUserId":self.noseeFriend,
                             @"itIsPaid":itIsPaid,  //1 有偿 2 无偿
                             @"images":self.imageStr,
                             @"money":self.red.length>0?self.red:@"0",
                             @"cityName":self.userCity
                             };
    [BGMHTTP requestWithMethodName:@"publish/savePublish" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSString *code = [NSString stringWithFormat:@"%@",[result objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            [self gotoPushSuccessVC:[NSString stringWithFormat:@"%@",[result objectForKey:@"data"]]];
        }else{
            NSLog(@"------发布信息失败 %@------",code);
        }

    }];
}
#pragma mark 添加图片
-(void)deleAddImage:(UIButton *)btn{
    if(self.imageArray.count==0){
        return ;
    }
    int i = (int)btn.tag;
    [self.imageArray removeObjectAtIndex:i];
    [self reloadImageView];
}
- (void)clickAddImage{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消 " style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                            
                                                         }];
    UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                             //响应事件
                                                              [self openCarme];
                                                             
                                                         }];
    UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction * action) {
                                                           //响应事件
                                                 [self openPhotoImage];
                                                       }];
    [alert addAction:saveAction];
    [alert addAction:cancelAction];
    [alert addAction:deleteAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void)openCarme{
    // 判断系统是否支持相机
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = NO;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
// 获取图片后操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *) kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImage *edit = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self.imageArray addObject:edit];
        [self reloadImageView];
    }
//
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
    
}
- (void)reloadImageView{
    ////////
    dispatch_async(dispatch_get_main_queue(), ^{
        int i = 0;
        if (self.imageArray.count<3) {
            i = 1;
        }else if (self.imageArray.count<6){
            i = 2;
        }else{
            i = 3;
        }
        self.imageH = i * 130.0;
        
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
        [self.messageTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    });
    
    
    
}



#pragma mark textViewDelegate
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.pushTitle = textField.text;
    [textField resignFirstResponder];
}
- (void)textFieldDidChange:(UITextField *)textField
{
    if(_maxLength <= 0){
        return;
    }
    
    NSString *text = textField.text;
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    //没有高亮选择的字，则对已输入的文字进行字数统计和限制,防止中文/emoj被截断
    if (!position){
        if (text.length > _maxLength){
            NSRange rangeIndex = [text rangeOfComposedCharacterSequenceAtIndex:_maxLength];
            if (rangeIndex.length == 1){
                textField.text = [text substringToIndex:_maxLength];
            }else{
                if(_maxLength == 1){
                    textField.text = @"";
                }else{
                    NSRange rangeRange = [text rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, _maxLength - 1 )];
                    textField.text = [text substringWithRange:rangeRange];
                }
            }
            
        }
    }
}




- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if(_maxLength <= 0){
        return YES;
    }
    
    UITextRange *selectedRange = [textField markedTextRange];//高亮选择的字
    UITextPosition *startPos = [textField positionFromPosition:selectedRange.start offset:0];
    UITextPosition *endPos = [textField positionFromPosition:selectedRange.end offset:0];
    NSInteger markLength = [textField offsetFromPosition:startPos toPosition:endPos];
    
    NSInteger confirmlength =  textField.text.length - markLength - range.length;//已经确认输入的字符长度
    if(confirmlength >= _maxLength ){
        return NO;
    }
    
    NSInteger allowMaxMarkLength = [self allowMaxMarkLength:_maxLength - confirmlength];
    if(markLength > allowMaxMarkLength ){// && string.length > 0){
        return NO;
    }
    return YES;
    
}
/**
 主要是用于中文输入的场景，可根据需要自定义
 剩余的允许输入的字数较少时，限制拼音字符的输入，提升体验
 */
- (NSInteger)allowMaxMarkLength:(NSInteger)remainLength
{
    NSInteger length = 0;
    if(remainLength > 2){
        length = NSIntegerMax;
    }else if(remainLength > 0){
        length = remainLength * 6;  //一个中文对应的拼音一般不超过6个
    }
    
    return length;
}

- (void)textViewDidEndEditing:(UITextView *)textView{
    self.pushContent = textView.text;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    self.pushTitle = textField.text;
    [textField resignFirstResponder];
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView{
    
    UITableViewCell *cell = (UITableViewCell *)[textView superview];
    UILabel *label = (UILabel *)[cell viewWithTag:100];
    if(textView.text.length==0){
        label.hidden = NO;
    }else if (textView.text.length>0){
        label.hidden = YES;
    }
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        self.pushContent = textView.text;
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}
#pragma mark 相册
- (QBImagePickerController*)qb_picker{
    if (!_qb_picker) {
        _qb_picker = [QBImagePickerController new];
        _qb_picker.delegate = self;
        _qb_picker.showsNumberOfSelectedAssets = YES;
        _qb_picker.allowsMultipleSelection = YES;
    }
    [_qb_picker.selectedAssets removeAllObjects];
    return _qb_picker;
}
-(void)openPhotoImage{
    self.qb_picker.maximumNumberOfSelection = 9-self.imageArray.count;
    [self presentViewController:self.qb_picker animated:YES completion:nil];
}
- (UIImagePickerController*)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController  = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = NO;//设置可编辑
    }
    return _imagePickerController;
}
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    
        if (assets.count == 0) {
             [self dismissViewControllerAnimated:YES completion:nil];
            return ;
        }else{
            [self getLibraryPhotoImage:assets];
          
        }
         [self dismissViewControllerAnimated:YES completion:nil];
}



- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController{
    [self dismissViewControllerAnimated:YES completion:nil];

}

//- (BOOL)qb_imagePickerController:(QBImagePickerController *)imagePickerController shouldSelectAsset:(PHAsset *)asset{
//
//}
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(PHAsset *)asset{
    
}
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didDeselectAsset:(PHAsset *)asset{
    
}


- (void)getLibraryPhotoImage:(NSArray *)assets{

    dispatch_async(dispatch_get_main_queue(), ^{
        for (PHAsset *asset in assets) {
           
            PHImageManager * imageManager = [PHImageManager defaultManager];
            [imageManager requestImageDataForAsset:asset options:nil resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                UIImage * image = [UIImage imageWithData:imageData];
                 [self.imageArray addObject:image];
                [self reloadImageView];
            }];

        }
    });
}


#pragma mark 发布成功后
- (void)gotoPushSuccessVC:(NSString *)messageID{
    dispatch_async(dispatch_get_main_queue(), ^{
        PushSuccessViewController *vc = [[PushSuccessViewController alloc]init];
        vc.messageID = messageID;
        [self.navigationController pushViewController:vc animated:YES];
    });
}

- (void)clickBack{
    if (self.red.length>0) {
        
#pragma mark 退回app余额
        [SVProgressHUD showInfoWithStatus:@"确定要取消发布吗？红包将退还到你的余额！"];
        [self payReturn];
        [self performSelector:@selector(pushVCDismiss) withObject:nil afterDelay:1];
    }else{
        [self pushVCDismiss];
    }
    
}
#pragma mark 红包退回
- (void)payReturn{
    
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,
                            @"userId":[BGMUser shareInstance].userId,
                            @"returnMoney":self.red
                            };
    [BGMHTTP requestWithMethodName:@"publish/payReturn" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSLog(@"adsfsafsaf");
    }];
    
    
}


- (void)pushVCDismiss{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/** 代理方法返回省市区*/
- (void)GFAddressPickerWithProvince:(NSString *)province
                               city:(NSString *)city area:(NSString *)area{
    
    self.userCity = city;
    self.pickerView.hidden = YES;
    
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:5 inSection:0];
    [self.messageTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
 
}
/** 取消代理方法*/
- (void)GFAddressPickerCancleAction{
    self.pickerView.hidden = YES;
}

@end
